package com.china.zhuoyue.map.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.MyLocationStyle
import com.china.zhuoyue.map.viewmodel.MapViewModel
import com.china.zhuoyue.ui.ext.toColor


open class MapFragment : Fragment() {
    private val mMapViewModel: MapViewModel by activityViewModels()

    private var mMapView: MapView? = null
    private var aMap: AMap? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mMapView = MapView(
            context,
//            AMapOptions()
//                .camera(
//                    CameraPosition.builder()
//                        .zoom(16f)
//                        .build()
//                )
        )
        mMapView?.onCreate(savedInstanceState)
        aMap = mMapView?.map?.apply {
            uiSettings.apply {
                isZoomControlsEnabled = false
                isMyLocationButtonEnabled = true
            }
        }
        val myLocationStyle = MyLocationStyle().apply {
            myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
//            myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE)
            interval(2000)
            radiusFillColor(android.R.color.transparent.toColor())
            strokeWidth(0f)
        }
        aMap?.myLocationStyle = myLocationStyle
        aMap?.isMyLocationEnabled = true

        aMap?.moveCamera(CameraUpdateFactory.zoomTo(16f))
        aMap?.addOnMyLocationChangeListener {
            mMapViewModel.mLocationChange.value = it
        }
        return mMapView
    }


    override fun onDestroy() {
        super.onDestroy()
        mMapView?.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        mMapView?.onResume()
//        getLocation {
//            it?.let {
//                aMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(it.latitude, it.longitude), 16f))
//            }
//        }
    }

    override fun onPause() {
        super.onPause()
        mMapView?.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mMapView?.onSaveInstanceState(outState)
    }
}